<?php
namespace Home\Controller;
use Think\Controller;
class RoleController extends BaseController{
    public function add(){
//        print_r($_POST);
        if(IS_AJAX){
            $role_name = trim(I('post.role_name'));
            $jibie = trim(I('post.jibie'));
            if($role_name==''){
                show(0,'角色名称不能为空');
            }
            $data['role_name'] = $role_name;
            $data['jibie'] = $jibie;
            if($id=D('Role')->add($data)){
                show(1,'角色添加成功');
            }else{
                show(0,'角色添加失败');
            }
        }else{
            $priModel = D('privilege');
            $priData = $priModel->getTree();

            //获取地区级别
            $roleData = D('Qujieshequ')->getTree();
            $this->assign('roleData',$roleData);

            $this->assign('priData',$priData);
            $this->display();
        }
    }
    public function lst(){
        $roleModel = D('role');
        $data = $roleModel->order('jibie asc')->select();
        $count = $roleModel->count();

        $this->assign('data',$data);
        $this->assign('count',$count);
        $this->display('index');
    }
    public function edit(){
        $id = I('get.id');
        if(IS_AJAX){
            $data['role_name'] = I('post.role_name');
            $data['parent_id'] = I('post.parent_id');
            $data['id'] = I('post.id');
            if((D('Role')->save($data)) !== false){
                show(1,'修改成功');
            }else{
                show(0,'修改失败');
            }
        }else{
            //所有的权限
            $priModel = D('privilege');
            $priData = $priModel->getTree();
            $this->assign('priData',$priData);

            //取出当前角色所拥有的权限id
            $rpModel = M('RolePrivilege');
            //得到一个一维数组["pri_id"] => string(9) "1,6,7,8,9"(也可以当做是一个字符串)
            $rpData = $rpModel->field('GROUP_CONCAT(pri_id) pri_id')->where(array('role_id'=>array('eq',$id)))->find();
            //将这个字符串转化为数组(一维数组)
            $rpData = explode(',',$rpData['pri_id']);
            $this->assign('rpData',$rpData);

            //取出当前角色的名称和id
            $RoleModel = D('Role');
            $data = $RoleModel->find($id);
            $this->assign('data', $data);



            $roleData = D('Qujieshequ')->getTree();
            $this->assign(array(
                'roleData'=>$roleData,
            ));

            $this->display();
        }
    }
    public function del(){
        $id = I('post.id',0);  //如果没有参数就是默认值0
        $ids = D("Role")->delete($id);  //删除之前有钩子函数
        if($ids !== false){//删除成功
            return show(1,'删除成功!');
        }else{
            return show(0,'删除失败!(可能有管理员属于这个角色)');
        }
    }
}